<template>
    <div class="init page-box">
        <Card>
            <Row>
                <i-col span="22">
                    <span class="inline-block">
                    <span style="text-align: right">业务日期</span>
                    <DatePicker
                        v-model="formItemSearch.date"
                        type="daterange"
                        class="search-input"
                        range-separator="-"
                        placeholder="请选择"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </DatePicker>
                    </span>

                    <span class="inline-block">
                        <span style="text-align: right">园区</span>
                        <Select v-model="ccisWhId" class="search-input" clearable @on-change="ccisWhChange">
                            <Option v-for="item in wareList" :value="item.id" :key="item.id"
                                    :label="`${item.whName}(${item.whCode})`">{{ `${item.whName}(${item.whCode})` }}</Option>
                        </Select>
                    </span>
                    <span class="inline-block">
                        <span style="text-align: right">仓库</span>
                        <Select v-model="formItemSearch.whCodes" class="search-input" clearable multiple>
                        <Option v-for="item in whCodeList" :value="item.whCode" :key="item.whCode"
                                :label="`${item.whName}(${item.whCode})`">{{ `${item.whName}(${item.whCode})` }}</Option>
                        </Select>
                    </span>
                    <span class="button-space inline-block">
                        <span style="text-align: right">货主/结算客户</span>
                        <Select
                            v-model="formItemSearch.ownerCodeList"
                            :disabled="!$utils.getUserInfo().currentAgentPermission"
                            :max-tag-count="1"
                            multiple
                            filterable
                            size="small"
                            class="search-input"
                            style="width: 400px"
                        >
                            <Option
                                v-for="(item, index) in ownerCodeList"
                                :key="index"
                                :value="item.ownerCode"
                                :label="item.ownerName"
                            ></Option>
                        </Select>
                    </span>

                    <Button size="small" type="primary" class="button-space" @click="search">查询</Button>
                    <Button type="primary" size="small" class="button-space" @click="reset">重置</Button>
                    <Button type="primary" size="small" class="button-space" @click="exportData()">导出</Button>
<!--                    <Button type="primary" size="small" class="button-space" @click="exportSumData('导出日业务汇总报表', 1)">导出日业务汇总</Button>-->
<!--                    <Button type="primary" size="small" class="button-space" @click="exportSumData('导出日反馈', 2)">导出日反馈</Button>-->
                </i-col>
                <i-col span="2" style="text-align: right">
                    <data-tips content="按照业务的开始时间汇总每天的业务量" />
                </i-col>
            </Row>
            <daily-table
                ref="dailyTable"
                style="margin-top: 10px"
                :search-params="formItemSearch"
                :manageCompanyList="manageCompanyList"
                :ownerCodeList="ownerCodeList"
                :whCodeList="whCodeList"
                :wms-url="wmsUrl"
                :show-table="showTable"
            ></daily-table>

            <Modal
                :value="exportInfoShow"
                :title="exportInfoTitle"
                width="400"
                :mask-closable="false"
                :closable="false"
                @on-ok="onExportOk"
                @on-cancel="onExportCancel">
                <Form
                    :model="exportFormItem"
                    ref="exportForm"
                    :label-width="70"
                    :rules="ruleValidate">
                    <Row>
                        <i-col span="24">
                            <FormItem label="导出日期">
                                <Row>
                                    <DatePicker v-model="time" type="datetimerange" format="yyyy-MM-dd HH:mm:ss" placeholder="请选择导出日期" @on-change="timeChange" size="small" style="width: 280px" clearable></DatePicker>
                                </Row>
                            </FormItem>
                        </i-col>
                    </Row>
                </Form>
                <div slot="footer">
                    <Button
                        size="small"
                        type="primary"
                        @click="onExportOk"
                        :loading="exportBtnLoading">导出
                    </Button>
                    <Button type="warning" size="small" @click="onExportCancel">取消</Button>
                </div>
            </Modal>
        </Card>
    </div>
</template>

<script>
import DailyTable from "./component/daily-table"; //okok  vuex除外
import {
    getAllWareData,
    getAllCompany,
    getAllOwner,
    getOwnerDataList,
    exportDayBusinessSummary,
    exportDayFeedback,
    getAllType,
    getAllWareList, selectCustomerInfoByDto
} from '@/api/warehouse/home.js';
import {mapState} from "vuex";
import fileDownload from "js-file-download";
import DataTips from "./component/dataTips";
import { getCurrentAgentPermissionWareHouse } from '@/libs/handleWareHouseList';
export default {
    name: "whDaily",
    components: {
        DataTips,
        DailyTable
    },
    data() {
        return {
            showTable: false,
            customerCode: '',
            wareList: [],
            wmsUrl: '',
            ccisWhId: '',
            formItemSearch: {
                ownerCodeList: [],
                notInMatTypeCodeList: ["9999", "0001"],
                startTime: new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 6)),
                endTime: new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 1)),
                date: [new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 6)), new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 1))],
            },
            whCodeList: [],
            defaultOwnerCodeList: [],
            ownerCodeList: [],
            manageCompanyList: [],
            businessTypeList: [],
            customerCodeList: [],
            sumDayStatisticsParam: {
                startTime: '',
                endTime: '',
                inOrOutPut: 'in'
            },
            exportLoading: false,
            exportInfoShow: false,
            exportBtnLoading: false,
            exportInfoTitle: '',
            exportFormItem: {
                startDate: null,
                endDate: null,
                date: [new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 1)).setHours(6), new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate())).setHours(6)],
            },
            ruleValidate: {
                startDate: [{required: true, message: '导出开始日期必填', trigger: 'change', type: 'date'}],
                endDate: [{required: true, message: '导出结束日期必填', trigger: 'change', type: 'date'}],
            },
            time: [this.formatDateTime(new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 1)).setHours(6)),this.formatDateTime(new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate())).setHours(6))]
        }
    },
    computed: {
        ...mapState('common', {
            matTypeList: (state) => state.matTypeList
        })
    },
    methods: {
        exportData() {
            this.$refs.dailyTable.exportExcel(this.formItemSearch, this.wmsUrl, this.ccisWhId);
        },
        loginOut() {
            this.$Modal.confirm({
                title: '提示',
                content: '网络错误！！！',
                okText: '退出系统',
                cancelText: '取消',
                onOk: () => {
                    this.$auth.logout({
                        success: function () {
                        },
                        error: function () {
                        }
                    });
                },
                onCancel: () => {
                    return false;
                }
            });
        },
        getBusinessTypeList() {
            getAllType('UPLOAD_FILE_TYPE', this.wmsUrl).then(response => {
                if (response.data.returnCode === 200) {
                    this.businessTypeList = response.data.returnData;
                } else {
                    this.$error(response.data.returnMsg, 3);
                }
            }).catch(err => {
                this.loginOut();
            });
        },
        getWareHouse(response) {
            if (response.data.returnCode === 200) {
                this.whCodeList = response.data.returnData
                if (this.whCodeList.length !== 0) {
                    this.formItemSearch.whCodes = []
                    this.formItemSearch.whCodes.push(this.whCodeList[0].whCode);
                }
            } else {
                this.$error(response.data.returnMsg, 3)
            }
        },
        getManageCompanyList(response) {
            if (response.data.returnCode === 200) {
                this.manageCompanyList = response.data.returnData
                if (this.manageCompanyList.length) {
                    this.manageCompanyList.forEach(item => {
                        item.id = item.id.toString()
                    })
                }
                this.formItemSearch.manageCompanyCodeList = [];
                if (this.manageCompanyList.length === 1) {
                    this.formItemSearch.manageCompanyCodeList.push(this.manageCompanyList[0].id);
                }
            } else {
                this.$error(response.data.returnMsg, 3)
            }
        },

        // 查询
        search() {
            if (!this.formItemSearch.date) {
                this.$error('请选择统计日期', 3);
                return;
            }
            this.formItemSearch.startTime = this.formItemSearch.date[0];
            this.formItemSearch.endTime = this.formItemSearch.date[1];
            this.getData();
        },
        // 重置
        reset() {
            this.formItemSearch = {
                startTime: new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 6)),
                endTime: new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 1)),
                date: [new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 6)), new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 1))],
                notInMatTypeCodeList: ["9999", "0001"],
                ownerCodeList: this.defaultOwnerCodeList,
            };
            this.getData();
        },
        getData() {
            this.$nextTick(() => {
                this.$refs.dailyTable.initGridData(this.formItemSearch, this.wmsUrl);
                this.$refs.dailyTable.getSumData(this.formItemSearch, this.wmsUrl);
            })
        },
        // 导出
        exportExcel() {
            this.exportLoading = true;
            this.$refs.dailyTable.exportOut();
            this.exportLoading = false;
        },
        onExportOk() {
            // console.log(this.time[0], this.time[1], '时间')
            if (this.time[0] === '' || this.time[1] === '' || this.time[0] === null || this.time[1] === null) {
                this.$error('请选择导出时间', 3);
                return;
            }
            this.exportBtnLoading = true

            // this.exportFormItem.startDate = new Date(Date.parse(new Date(this.formatDateTime(this.exportFormItem.date[0]))) + 8 * 3600 * 1000);
            // this.exportFormItem.endDate = new Date(Date.parse(new Date(this.formatDateTime(this.exportFormItem.date[1]))) + 8 * 3600 * 1000);
            // this.exportFormItem.startDate = new Date(this.formatDateTime(this.exportFormItem.date[0]));
            // this.exportFormItem.startDate = new Date(this.formatDateTime(this.exportFormItem.date[0]));
            // this.exportFormItem.endDate = new Date(this.formatDateTime(this.exportFormItem.date[1]));
            this.exportFormItem.startDate = new Date(this.time[0]);
            this.exportFormItem.endDate = new Date(this.time[1]);
            if (this.exportInfoTitle === '导出日业务汇总报表') {
                exportDayBusinessSummary(this.exportFormItem, this.wmsUrl).then(response => {
                    this.exportBtnLoading = false;
                    if (response.data.returnCode === 400) {
                        this.$error(response.data.returnMsg, 3)
                    } else {
                        fileDownload(response.data, '日业务汇总信息.xlsx')
                    }
                }).catch(err => {
                    this.exportBtnLoading = false;
                    this.loginOut()
                })
            }
            if (this.exportInfoTitle === '导出日反馈') {
                exportDayFeedback(this.exportFormItem, this.wmsUrl).then(response => {
                    this.exportBtnLoading = false;
                    if (response.data.returnCode === 400) {
                        this.$error(response.data.returnMsg, 3)
                    } else {
                        fileDownload(response.data, '日反馈汇总信息.xlsx')
                    }
                }).catch(err => {
                    this.exportBtnLoading = false;
                    this.loginOut()
                })
            }
        },
        onExportCancel() {
            this.exportInfoShow = false
            this.exportBtnLoading = false;
        },
        exportSumData(title, type) {
            this.exportInfoTitle = title
            this.exportInfoShow = true
            this.exportFormItem = {
                startDate: null,
                endDate: null,
                date: [new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 1)).setHours(6), new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate())).setHours(6)],
            }
            this.time = [this.formatDateTime(new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate() - 1)).setHours(6)),this.formatDateTime(new Date(new Date(new Date().toLocaleDateString()).setDate(new Date().getDate())).setHours(6))]
        },
        formatDateTime(inputTime) {
            var date = new Date(inputTime); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
            var h = (date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours()) + ':';
            var m = (date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes()) + ':';
            var s = date.getSeconds() < 10 ? ('0' + date.getSeconds()) : date.getSeconds();
            return Y + M + D + h + m + s;
        },
        // 每次获取传入的时间都是格式化时间，但绑定的time其实是中国标准时间吗
        timeChange(time1){
            // console.log(time1, 'time1')
            // if(time1[1].slice(-8) === '06:00:00'){
            //   time1[1] = time1[1].slice(0,-8) + '06:00:00'
            //   // 由于this.time是标准日期，因此必须使用这样的语句
            //   this.time= time1
            // }
            if (this.time[0] !== '' && this.time[1] !== '') {
                this.time = [time1[0].slice(0,-8) + '06:00:00', time1[1].slice(0,-8) + '06:00:00']
            }
        },
        async getCurrentData() {
            const companyResponse = await getAllCompany(this.wmsUrl);
            const wareResponse = await getAllWareData(this.wmsUrl);
            this.getWareHouse(wareResponse);
            this.getManageCompanyList(companyResponse);
            this.getData();
        },
        async initData(flag) {
            if (flag) {
                const { data, message } = await getCurrentAgentPermissionWareHouse();
                if (data) {
                    this.wareList = data;
                    this.wmsUrl = this.wareList[0].ipProt;
                    this.ccisWhId = this.wareList[0].id;
                    if (this.wareList[0].whName === '宁波冷库') {
                        this.showTable = true;
                    }
                } else if (message) {
                    this.$error(message, 3)
                }
            }
            await this.getOwnerCodeList();
            this.getBusinessTypeList();
            this.getCurrentData();
        },
        async ccisWhChange(val) {
            if (val === 37) {
                this.showTable = true;
            }else {
                this.showTable = false;
            }
            let data = this.wareList.filter(x => x.id === val)[0];
            this.wmsUrl = data.ipProt;
            this.initData();
        },

        async getOwnerCodeList() {
          const { currentAgentPermission, customerInfoList, entrustingPartyCode } = this.$utils.getUserInfo();
          const codeList = customerInfoList.map(i => i.customerPartyCode);
            const params = currentAgentPermission ? { ccisCustomerCodeList: codeList} : { ccisCustomerCode: entrustingPartyCode };
            const response = await selectCustomerInfoByDto(params, this.wmsUrl);
            const res = await getAllOwner(this.wmsUrl);
            const { returnCode, returnData, returnMsg } = response.data;
            const { returnCode: code, returnData: data, returnMsg: msg } = res.data;
            if (returnCode !== 200) {
                this.$Message.error(returnMsg);
            }
            if (code !== 200) {
                this.$Message.error(msg);
            }
          this.ownerCodeList = data;
            if (!currentAgentPermission) {
              this.formItemSearch.ownerCodeList = codeList;
              this.defaultOwnerCodeList = codeList;
            }
          // if (returnData && returnData.length && data && data.length) {
          //       if (currentAgentPermission) {
          //           this.ownerCodeList = data.filter(c => returnData.some(i => i.customerCode === c.ownerCode));
          //       } else {
          //           this.ownerCodeList = data;
          //       }
          //       this.formItemSearch.ownerCodeList = returnData.map(i => i.customerCode);
          //   } else {
          //       this.ownerCodeList = [];
          //       this.formItemSearch.ownerCodeList = [];
          //   }
          //   this.defaultOwnerCodeList = this.formItemSearch.ownerCodeList.map(i => i);
        }
    },
    created() {},
    watch: {
        '$store.state.user.userInfo': {
            async handler(value) {
                if (!value || !value.entrustingPartyCode) return;
                this.initData(true);
            },
            deep: true,
            immediate: true
        }
    }
}
</script>

<style scoped>
@import './common.less';
</style>
